package com.lagou.edu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author stevejson
 */
@Slf4j
@Component
@RefreshScope
public class BrushStrokeFilter implements GlobalFilter, Ordered {
    private static ConcurrentHashMap<String, CopyOnWriteArrayList<Long>> ipRequestMap=new ConcurrentHashMap<>();
    @Value("${brushStroke.time}")
    public int time;
    @Value("${brushStroke.number}")
    public int number;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String path=request.getPath().toString();
        if(path.startsWith("/api/code/create")){
            // 从request对象中获取客户端ip
            String clientIp = Objects.requireNonNull(request.getRemoteAddress()).getHostString();

            //判断方法是否存在于map中
            if(!ipRequestMap.containsKey(clientIp)){
                CopyOnWriteArrayList<Long> list= new CopyOnWriteArrayList<Long>();
                list.add(System.currentTimeMillis());
                ipRequestMap.put(clientIp,list);
            }else{
                //判断ipRequestMap中得请求次数是否超了
                CopyOnWriteArrayList<Long> list=ipRequestMap.get(clientIp);
                List<Long> removeList = new ArrayList<>();
                //请求总数
                int requestCount=0;
                //当前时间
                Long now=System.currentTimeMillis();
                for (Long requestTime : list) {
                    if(now-requestTime <= time*60*1000){
                        requestCount++;
                    }else{
                        removeList.add(requestTime);
                    }
                }
                list.removeAll(removeList);
                System.out.println(clientIp+"::"+list);
                //判断请求次数是否超过阈值
                if(requestCount>=number){
                    // 决绝访问，返回
                    response.setStatusCode(HttpStatus.FORBIDDEN);
                    log.info("=====>IP:" + clientIp + " 暴刷");
                    String data = "您频繁进⾏注册，请求已被拒绝!";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }else{
                    ipRequestMap.get(clientIp).add(System.currentTimeMillis());
                }
            }
        }

        // 合法请求，放⾏，执⾏后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
